# -*- coding: utf-8 -*-
#
# Copyright (c) 2012, Rafael Pivato
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of Rafael Pivato nor the names of its contributors
#       may be used to endorse or promote products derived from this
#       software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL RAFAEL PIVATO BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

from datetime import datetime
from google.appengine.ext import db
from google.appengine.api import memcache


class Account(db.Model):
    """Model for a member user of this application."""

    email = db.EmailProperty(required=True)
    created = db.DateTimeProperty(required=True)
    locked = db.BooleanProperty(default=False)
    name = db.StringProperty(required=True)
    member_until = db.IntegerProperty(default=0)
    role = db.StringProperty(required=True, choices=['admin', 'officer',
                                                     'member', 'public'])

    def change_main(self, name):
        """Changes the main name for this account and update cache."""
        self.name = name.capitalize()
        self.put()
        key = 'ACCOUNT_%s' % (self.key().name())
        memcache.set(key, self)

    @classmethod
    def get_by_user_id(cls, user_id):
        """Gets an account by its user id."""
        client = memcache.Client()
        key = 'ACCOUNT_%s' % (user_id)
        value = client.gets(key)
        if value is None:
            account = cls.get_by_key_name(user_id)
            time = 0
            if account is None:
                new_value = False
                time = 300
            else:
                new_value = account
            if client.cas(key, new_value, time=time):
                value = new_value
            else:
                value = client.get(key)
                if value is None:
                    value = new_value
        if value is False:
            return None
        else:
            return value

    @classmethod
    def create_for_user_id(cls, user_id, **kwds):
        """Creates the new account and updates the cache."""
        kwds['created'] = datetime.utcnow()
        model = Account(key_name=user_id, **kwds)
        model.put()
        key = 'ACCOUNT_%s' % (user_id)
        memcache.set(key, model)
        return model

    @classmethod
    def update_for_user_id(cls, user_id, **kwds):
        """Updates an existing account attributes and updates the cache."""
        model = cls.get_by_user_id(user_id)
        for name, value in kwds.items():
            setattr(model, name, value)
        model.put()
        key = 'ACCOUNT_%s' % (user_id)
        memcache.set(key, model)
        return model

    @classmethod
    def update_membership(cls, user_id, name, member_until, role):
        """Updates the given account membership according to the main char."""
        model = cls.get_by_user_id(user_id)
        if model and model.name.lower() == name.lower() and \
        model.key().name() == user_id and \
        (model.member_until != member_until or model.role != role):
            model.member_until = member_until
            model.role = role
            model.put()
            key = 'ACCOUNT_%s' % (user_id)
            memcache.set(key, model)

    @classmethod
    def is_valid_role(cls, role):
        """Checks if a given role is valid."""
        return role in cls.role.choices

    @classmethod
    def cmp_roles(cls, role1, role2):
        """Makes a comparison between two valid roles."""
        return cmp(cls.role.choices.index(role1),
                   cls.role.choices.index(role2)) * -1

    @classmethod
    def latest_created(cls):
        query = cls.all()
        query.order('-created')
        return query.fetch(50)
